package com.tsinghuabigdata.edu.ddmath.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tsinghuabigdata.edu.ddmath.MVPModel.MyStudyModel;
import com.tsinghuabigdata.edu.ddmath.MVPModel.RequestListener;
import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.activity.MainActivity;
import com.tsinghuabigdata.edu.ddmath.module.login.view.LoginActivity;
import com.tsinghuabigdata.edu.ddmath.module.login.view.RegisterActivity;
import com.tsinghuabigdata.edu.ddmath.module.onlineTutoring.SelectQuestionsActivity;
import com.tsinghuabigdata.edu.ddmath.adapter.CoursePagerAdapter;
import com.tsinghuabigdata.edu.ddmath.bean.ClassInfo;
import com.tsinghuabigdata.edu.ddmath.bean.LoginInfo;
import com.tsinghuabigdata.edu.ddmath.bean.StudentsBean;
import com.tsinghuabigdata.edu.ddmath.bean.TeacherBean;
import com.tsinghuabigdata.edu.ddmath.bean.UserDetailinfo;
import com.tsinghuabigdata.edu.ddmath.commons.http.HttpResponse;
import com.tsinghuabigdata.edu.ddmath.module.mycenter.SetHeadImage;
import com.tsinghuabigdata.edu.ddmath.util.AccountUtils;
import com.tsinghuabigdata.edu.ddmath.util.AppLog;
import com.tsinghuabigdata.edu.ddmath.util.DataUtils;
import com.tsinghuabigdata.edu.ddmath.util.DensityUtils;
import com.tsinghuabigdata.edu.ddmath.util.ToastUtils;
import com.tsinghuabigdata.edu.ddmath.util.WindowUtils;
import com.tsinghuabigdata.edu.ddmath.view.CircleImageView;

import java.util.ArrayList;
import java.util.List;


/**
 * 我的学习
 * Created by Administrator on 2016/12/14.
 */

public class MyStudyFragment extends MyBaseFragment implements View.OnClickListener {

    private static final String TAG = "MyStudyFragment";

    private Context mContext;
    private MyStudyModel mMyStudyModel = new MyStudyModel();

    private ImageView       mIvDoudouteng;
    private TextView        mTvDoudouWork;
    private TextView        mTvOtherWork;
    private TextView        mTvOnlineTutoring;
    private View            mSlider;
    private LinearLayout    mLlClass;
    private TextView        mTvCourseName;
    private CircleImageView mIvTeacherHead1;
    private TextView        mTvTeacherName1;
    private CircleImageView mIvTeacherHead2;
    private TextView        mTvTeacherName2;
    private LinearLayout    mLlClassmate;
    private CircleImageView mIvClassmate1;
    private TextView        mTvClassmate1;
    private CircleImageView mIvClassmate2;
    private TextView        mTvClassmate2;
    private CircleImageView mIvClassmate3;
    private TextView        mTvClassmate3;
    private ImageView       mIvDoudouCamera;
    private ImageView       mIvDoudouHi;
    private ImageView       mIvHi;
    //    private LinearLayout    mLlCourseContent;
    private ViewPager       mViewPager;
    private LinearLayout    mLlUnregisterTips;
    private LinearLayout    mLlUnregisterPic;
    private Button          mBtnRegister;
    private Button          mBtnLogin;
    private LinearLayout    mLlNoClassTips;

    private MainActivity mainActivity;
    private String       accessToken;
    private String       studentId;
    private String       classId;

    private String mLoginName;
    private int    tabWidth;
    private int currTabIndex = 0; //当前页卡编号

    private ArrayList<Fragment> courseFragments = new ArrayList<Fragment>();
    private AgencyWorkFragment     mAgencyWorkFragment;
    private SchoolWorkFragment     mSchoolWorkFragment;
    private OnlineTutoringFragment mOnlineTutoringFragment;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.i("burning", "MyStudyFragment onCreateView");
        View root = inflater.inflate(R.layout.fragment_my_study, container, false);
        initView(root);
        initFragment();
        initData();
        return root;
    }

    private void initView(View root) {
        mContext = getActivity();
        mainActivity = (MainActivity) getActivity();

        mIvDoudouteng = (ImageView) root.findViewById(R.id.iv_doudouteng);
        mTvDoudouWork = (TextView) root.findViewById(R.id.tv_doudou_work);
        mTvOtherWork = (TextView) root.findViewById(R.id.tv_other_work);
        mTvOnlineTutoring = (TextView) root.findViewById(R.id.tv_online_tutoring);
        mSlider = root.findViewById(R.id.slider);
        mLlClass = (LinearLayout) root.findViewById(R.id.ll_class);
        mTvCourseName = (TextView) root.findViewById(R.id.tv_course_name);
        mIvTeacherHead1 = (CircleImageView) root.findViewById(R.id.iv_teacher_head1);
        mTvTeacherName1 = (TextView) root.findViewById(R.id.tv_teacher_name1);
        mIvTeacherHead2 = (CircleImageView) root.findViewById(R.id.iv_teacher_head2);
        mTvTeacherName2 = (TextView) root.findViewById(R.id.tv_teacher_name2);
        mLlClassmate = (LinearLayout) root.findViewById(R.id.ll_classmate);
        mIvClassmate1 = (CircleImageView) root.findViewById(R.id.iv_classmate1);
        mTvClassmate1 = (TextView) root.findViewById(R.id.tv_classmate1);
        mIvClassmate2 = (CircleImageView) root.findViewById(R.id.iv_classmate2);
        mTvClassmate2 = (TextView) root.findViewById(R.id.tv_classmate2);
        mIvClassmate3 = (CircleImageView) root.findViewById(R.id.iv_classmate3);
        mTvClassmate3 = (TextView) root.findViewById(R.id.tv_classmate3);
        mIvDoudouCamera = (ImageView) root.findViewById(R.id.iv_doudou_camera);
        mIvDoudouHi = (ImageView) root.findViewById(R.id.iv_doudou_hi);
        mIvHi = (ImageView) root.findViewById(R.id.iv_hi);
        //        mLlCourseContent = (LinearLayout) root.findViewById(R.id.ll_course_content);
        mViewPager = (ViewPager) root.findViewById(R.id.view_pager);
        mLlUnregisterTips = (LinearLayout) root.findViewById(R.id.ll_unregister_tips);
        mLlUnregisterPic = (LinearLayout) root.findViewById(R.id.ll_unregister_pic);
        mBtnRegister = (Button) root.findViewById(R.id.btn_register);
        mBtnLogin = (Button) root.findViewById(R.id.btn_login);
        mLlNoClassTips = (LinearLayout) root.findViewById(R.id.ll_no_class_tips);
        ViewGroup.LayoutParams layoutParams = mIvDoudouteng.getLayoutParams();
        int fragmentWidth = WindowUtils.getScreenWidth(getActivity()) - DensityUtils.dp2px(getActivity(), 131);
        layoutParams.height = fragmentWidth * 90 / 1782;
        mIvDoudouteng.setLayoutParams(layoutParams);

        tabWidth = DensityUtils.dp2px(getActivity(), 132);

        mTvDoudouWork.setOnClickListener(this);
        mTvOtherWork.setOnClickListener(this);
        mTvOnlineTutoring.setOnClickListener(this);
        mBtnRegister.setOnClickListener(this);
        mBtnLogin.setOnClickListener(this);
    }

    //初始化三个Fragment————机构作业、学校作业、在线辅导
    private void initFragment() {
        mAgencyWorkFragment = new AgencyWorkFragment();
        mSchoolWorkFragment = new SchoolWorkFragment();
        mOnlineTutoringFragment = new OnlineTutoringFragment();
        courseFragments.add(mAgencyWorkFragment);
        courseFragments.add(mSchoolWorkFragment);
        courseFragments.add(mOnlineTutoringFragment);

        //给ViewPager设置适配器
        mViewPager.setOffscreenPageLimit(2);
        CoursePagerAdapter adapter = new CoursePagerAdapter(getChildFragmentManager(), courseFragments);
        mViewPager.setAdapter(adapter);
        //        mViewPager.setCurrentItem(0);
        mViewPager.setOnPageChangeListener(new MyOnPageChangeListener());
    }


    private void initData() {
        createLoginInfo();
    }

    private void createLoginInfo() {
        LoginInfo loginInfo = AccountUtils.getLoginUser();
        if (loginInfo != null) {
            accessToken = loginInfo.getAccessToken();
            mLoginName = loginInfo.getLoginName();
            Log.i(TAG, "accessToken=" + accessToken + "mLoginName=" + mLoginName);
            UserDetailinfo detailinfo = AccountUtils.getUserdetailInfo();
            if (detailinfo == null || detailinfo.getJoinedClassInfoList() == null || detailinfo.getJoinedClassInfoList().size() == 0) {
                showNoClassView();
            } else {
                classId = detailinfo.getJoinedClassInfoList().get(0).getClassId();
                studentId = detailinfo.getStudentId();
                Log.i(TAG, "classId=" + classId + "studentId=" + studentId);
                queryClass();
                showCourseContentView();
            }
        } else {
            showUnregisterView();
        }
    }

    //查询登录信息——展示 1、未登录 2、未加入班级 3、已加入班级
    public void queryLoginInfo() {
        LoginInfo loginInfo = AccountUtils.getLoginUser();
        if (loginInfo != null) {
            accessToken = loginInfo.getAccessToken();
            mLoginName = loginInfo.getLoginName();
            Log.i(TAG, "accessToken=" + accessToken + "mLoginName=" + mLoginName);
            UserDetailinfo detailinfo = AccountUtils.getUserdetailInfo();
            if (detailinfo == null || detailinfo.getJoinedClassInfoList() == null || detailinfo.getJoinedClassInfoList().size() == 0) {
                showNoClassView();
            } else {
                classId = detailinfo.getJoinedClassInfoList().get(0).getClassId();
                studentId = detailinfo.getStudentId();
                Log.i(TAG, "classId=" + classId + "studentId=" + studentId);
                queryClass();
                mAgencyWorkFragment.setId(accessToken,classId,studentId);
                mAgencyWorkFragment.queryData();
                mSchoolWorkFragment.setId(accessToken,classId,studentId,mLoginName);
                mSchoolWorkFragment.queryUploadSize();
                mSchoolWorkFragment.queryPhoto(true);
                mOnlineTutoringFragment.setId(accessToken,classId,studentId);
                mOnlineTutoringFragment.isTutorApplied();
                showCourseContentView();
            }
        } else {
            showUnregisterView();
        }
    }

    //查询班级老师和同学信息——展示2个老师、随机展示3个同学
    public void queryClass() {
        if (TextUtils.isEmpty(classId)) {
            return;
        }
        mMyStudyModel.queryClass(accessToken, classId, new RequestListener<ClassInfo>() {
            @Override
            public void onSuccess(ClassInfo vo) {
                Log.i(TAG, "queryClass onSuccess");
                if (vo == null) {
                    mainActivity.setQueryClassSuccess(false);
                    ToastUtils.showShort(getActivity(), R.string.server_error);
                    return;
                }
                mainActivity.setQueryClassSuccess(true);
                mTvCourseName.setText(vo.getClassName());
                TeacherBean teacherBean = vo.getTeacher();
                if (teacherBean != null) {
                    mTvTeacherName1.setText(teacherBean.getReallyName() + "老师");
                    SetHeadImage.setHeadIncomplete(getContext(), mIvTeacherHead1, teacherBean.getHeadImage(), R.drawable.ico_teacher_head_normal);
                }
                //// TODO: 2017/3/9 增加到2老师
                List<StudentsBean> studentsList = vo.getStudents();
                if (studentsList != null && studentsList.size() > 0) {
                    List<StudentsBean> otherList = DataUtils.getOtherStudents(studentsList, studentId);
                    int size = otherList.size();
                    if (size > 0) {
                        mLlClassmate.setVisibility(View.VISIBLE);
                        StudentsBean studentsBean1 = otherList.get(0);
                        if (studentsBean1 != null) {
                            String reallyName = DataUtils.getFormatName(studentsBean1.getReallyName());
                            mTvClassmate1.setText(reallyName);
                            SetHeadImage.setHeadIncomplete(getContext(), mIvClassmate1, studentsBean1.getHeadImage());
                        }
                    }
                    if (size > 1) {
                        StudentsBean studentsBean2 = otherList.get(1);
                        if (studentsBean2 != null) {
                            String reallyName = DataUtils.getFormatName(studentsBean2.getReallyName());
                            mTvClassmate2.setText(reallyName);
                            SetHeadImage.setHeadIncomplete(getContext(), mIvClassmate2, studentsBean2.getHeadImage());
                        }
                    }
                    if (size > 2) {
                        StudentsBean studentsBean3 = otherList.get(2);
                        if (studentsBean3 != null) {
                            String reallyName = DataUtils.getFormatName(studentsBean3.getReallyName());
                            mTvClassmate3.setText(reallyName);
                            SetHeadImage.setHeadIncomplete(getContext(), mIvClassmate3, studentsBean3.getHeadImage());
                        }
                    }
                }
                mLlClass.setVisibility(View.VISIBLE);
            }

            @Override
            public void onFail(HttpResponse<ClassInfo> response, Exception ex) {
                Log.i(TAG, "queryClass onFail");
                mainActivity.setQueryClassSuccess(false);
                ToastUtils.showShort(getActivity(), R.string.server_error);
            }
        });

    }

    //展示 1、未登录页面
    private void showUnregisterView() {
        makeTitleEnable(false);
        mLlUnregisterTips.setVisibility(View.VISIBLE);
        mLlNoClassTips.setVisibility(View.INVISIBLE);
        mViewPager.setVisibility(View.INVISIBLE);
        mLlClass.setVisibility(View.INVISIBLE);
    }

    //展示 2、未加入班级页面
    private void showNoClassView() {
        makeTitleEnable(false);
        mLlUnregisterTips.setVisibility(View.INVISIBLE);
        mLlNoClassTips.setVisibility(View.VISIBLE);
        mViewPager.setVisibility(View.INVISIBLE);
        mLlClass.setVisibility(View.INVISIBLE);
    }

    //展示 3、已加入班级页面
    private void showCourseContentView() {
        makeTitleEnable(true);
        mLlUnregisterTips.setVisibility(View.INVISIBLE);
        mLlNoClassTips.setVisibility(View.INVISIBLE);
        mViewPager.setVisibility(View.VISIBLE);
    }

    private void makeTitleEnable(boolean enable) {
        mTvDoudouWork.setEnabled(enable);
        mTvOtherWork.setEnabled(enable);
        mTvOnlineTutoring.setEnabled(enable);
        mSlider.setEnabled(enable);
    }

    @Override
    public void onResume() {
        Log.i(TAG, "MyStudyFragment onResume()");
        super.onResume();
        if (!TextUtils.isEmpty(mLoginName)) {
            mSchoolWorkFragment.queryUploadSize();
        }
    }

    //实现标题栏滑块动画以及被选中标题加粗
    private void select(int i) {
        Log.i(TAG, "select i= " + i);
        if (currTabIndex == i) {
            return;
        }
        Animation animation = new TranslateAnimation(currTabIndex * tabWidth, i * tabWidth, 0, 0);
        animation.setFillAfter(true);// True:图片停在动画结束位置
        animation.setDuration(300);
        mSlider.startAnimation(animation);
        if (i == 0) {
            mIvDoudouCamera.setVisibility(View.INVISIBLE);
            mIvDoudouHi.setVisibility(View.VISIBLE);
            mIvHi.setVisibility(View.VISIBLE);
            mTvDoudouWork.setTypeface(Typeface.DEFAULT_BOLD);
            mTvOtherWork.setTypeface(Typeface.DEFAULT);
            mTvOnlineTutoring.setTypeface(Typeface.DEFAULT);
        } else if (i == 1) {
            mIvDoudouCamera.setVisibility(View.VISIBLE);
            mIvDoudouHi.setVisibility(View.INVISIBLE);
            mIvHi.setVisibility(View.INVISIBLE);
            mTvDoudouWork.setTypeface(Typeface.DEFAULT);
            mTvOtherWork.setTypeface(Typeface.DEFAULT_BOLD);
            mTvOnlineTutoring.setTypeface(Typeface.DEFAULT);
        } else if (i == 2) {
            mIvDoudouCamera.setVisibility(View.INVISIBLE);
            mIvDoudouHi.setVisibility(View.VISIBLE);
            mIvHi.setVisibility(View.VISIBLE);
            mTvDoudouWork.setTypeface(Typeface.DEFAULT);
            mTvOtherWork.setTypeface(Typeface.DEFAULT);
            mTvOnlineTutoring.setTypeface(Typeface.DEFAULT_BOLD);
        }
        currTabIndex = i;
        controll(i);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_register:
                mainActivity.goActivity(RegisterActivity.class);
                break;
            case R.id.btn_login:
                mainActivity.goActivity(LoginActivity.class);
                break;
            case R.id.tv_doudou_work:
                select(0);
                mViewPager.setCurrentItem(0);
                break;
            case R.id.tv_other_work:
                select(1);
                mViewPager.setCurrentItem(1);
                break;
            case R.id.tv_online_tutoring:
                mViewPager.setCurrentItem(2);
                select(2);
                break;
            case R.id.cb_to_submit_more:

                break;
            case R.id.btn_select_tutor: {
                Intent intent = new Intent(getActivity(), SelectQuestionsActivity.class);
                startActivityForResult(intent, 0);
            }
            break;
        }
    }

    private void controll(int i) {
        Log.i(TAG, "MyStudyFragment restartRun i=" + i);
        if (i == 2) {
            mOnlineTutoringFragment.restartRun(true);
        } else {
            mOnlineTutoringFragment.restartRun(false);
        }
    }

    public void controllPolling(boolean poll) {
        Log.i(TAG, "MyStudyFragment restartRun " + poll);
        if (currTabIndex == 2) {
            if (poll) {
                mOnlineTutoringFragment.restartRun(true);
            } else {
                mOnlineTutoringFragment.restartRun(false);
            }
        }
    }


    public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            AppLog.i(TAG, "onPageSelected position= " + position);
            select(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }


}
